
<template>
  <div>
    <el-card class="box-card">
      <div class="hander_item">
        <el-form v-model="editExamTimeForm">
          <el-row :gutter="24">
            <el-col :span="5">
              <el-form-item prop="invExamTaskName">
                <div class="four-content bg-color">
                  考试任务：<el-tag>{{ editExamTimeForm.name }}</el-tag>
                </div>
              </el-form-item>
            </el-col>

            <el-col :span="5">
              <el-form-item prop="invExamStartData">
                <div class="four-content bg-color">
                  开考时间：{{ editExamTimeForm.startTime }}
                </div>
              </el-form-item></el-col
            >
            <el-col :span="5">
              <el-form-item prop="invExamEndData">
                <div class="four-content bg-color">
                  截止时间：{{ editExamTimeForm.endTime }}
                </div>
              </el-form-item></el-col
            >
            <el-col :span="5">
              <el-button round @click="editTimeVisible = true"
                >修改考试时间</el-button
              >
            </el-col>

            <el-col :span="4">
              <el-button type="danger" @click="clearTable"
                >清空监考端数据</el-button
              >
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <br />
    <el-card>
      <div>
        <el-row>
          <!-- 显示模式 -->
          <el-col :span="5">
            <el-select v-model="value" placeholder="显示模式" clearable>
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>

          <!-- 考试开关 -->
          <!-- <el-col :span="3">
            <el-button
              v-if="examStatus == true"
              @click="openExam"
              type="primary"
              >开放考试</el-button
            >
            <el-button v-else @click="closeExam" type="danger"
              >关闭考试</el-button
            >
          </el-col> -->

          <!-- 换机设置 -->
          <el-col :span="3">
            <el-button @click="openChangemaChine">换机配置</el-button>

            <changemachine
              :showFlag="changemachineDialog"
              @closeDialog="closeDialog"
              @close="closeForm"
            >
            </changemachine>
          </el-col>

          <!-- 修改考试时间 -->
          <el-col :span="3">
            <el-button @click="openEditDate">修改时长</el-button>
            <editdate
              :showFlag="editDateDialog"
              @closeDialog="closeDialog"
              @close="closeForm"
            ></editdate>
          </el-col>

          <!-- 导出答卷 -->
          <el-col :span="3">
            <el-button type="success" @click="downLoadStudentAnswer()"
              >导出答卷</el-button
            >
          </el-col>

          <!-- 搜索 -->
          <el-col :span="5">
            <el-input
              v-model="keyword"
              @keyup.native="keyup()"
              placeholder="请输入考生名称"
              clearable
            >
              <el-button
                @click="getInvExamStuList"
                slot="append"
                icon="el-icon-search"
              ></el-button>
            </el-input>
          </el-col>

          <!-- 批量修改 -->
          <el-col :span="3">
            <el-button
              style="margin-left: 30 px"
              @click="selectUpdateStudentState"
              v-if="sselectInvStudentList.length > 0"
              type="danger"
            >
              批量修改</el-button
            >
          </el-col>
        </el-row>
        <br />

        <!-- 数据列表 -->
        <el-table
          :data="tableData"
          @selection-change="selectInvStudent"
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="Manage" label="" align="center">
            <template slot-scope="scope">
              <span class="demo1" @click="showStu(scope.row)">管理考生</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="testPaperInfoName"
            label="考卷名称"
            height="60"
          >
          </el-table-column>

          <el-table-column prop="loginName" label="登录账号"> </el-table-column>
          <el-table-column prop="studentName" label="姓名"> </el-table-column>
          <el-table-column
            prop="lastLoginTime"
            label="登录时间 "
            min-width="150"
          >
          </el-table-column>
          <el-table-column prop="data" label="结束时间 " min-width="150">
          </el-table-column>
          <el-table-column
            prop="loginIp"
            label="考生计算机考试ip地址 "
            min-width="150"
          >
          </el-table-column>
          <el-table-column prop="status" label="状态 " width="80" height="60">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                active-color="#409EFF"
                inactive-color="#F56C6C"
                :active-value="0"
                :inactive-value="1"
                @change="changeEnabled(scope.row, scope.row.status)"
              />
            </template>
          </el-table-column>
          <el-table-column prop=" description" label="状态说明 " height="60">
          </el-table-column>
        </el-table>
      </div>
      <!-- 监考考生分页 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNumber"
        :page-sizes="[5, 10, 30, 40]"
        :page-size="pageSize"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-card>
    <br />

    <!-- 修改考试时间对话框 -->
    <el-dialog
      title="修改考试时间"
      :visible.sync="editTimeVisible"
      :close-on-click-modal="false"
      width="800px"
    >
      <!-- 修改考试时间表单 -->
      <el-form label-width="150px" :model="editExamTimeForm">
        <el-form-item label="考试任务名称" prop="name">
          <el-input v-model="editExamTimeForm.name"></el-input>
        </el-form-item>

        <el-form-item label="说明" prop="text">
          <el-input v-model="editExamTimeForm.text"></el-input>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <!-- 开始日期 -->
          <el-date-picker
            v-model="editExamTimeForm.startTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="截止时间" prop="endTime">
          <!-- 截止日期 -->
          <el-date-picker
            v-model="editExamTimeForm.endTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer">
        <el-button @click="editTimeVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateExamTask">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 管理考生对话框 -->
    <el-dialog
      title="管理考生"
      :visible.sync="editStudentVisible"
      :close-on-click-modal="false"
      width="800px"
    >
      <!-- 管理考生表单 -->
      <el-form label-width="150px" :model="editStatusForm">
        <el-form-item label="登录账号" prop="stuid">
          <el-input v-model="editStatusForm.stuid"></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="stuname">
          <el-input v-model="editStatusForm.stuname"></el-input>
        </el-form-item>

        <el-form-item label="考试状态" prop="status">
          <el-radio v-model="editStatusForm.status" label="0"
            >允许考试</el-radio
          >
          <el-radio v-model="editStatusForm.status" label="1"
            >禁止考试</el-radio
          >
        </el-form-item>

        <el-form-item label="禁考理由" prop="banReason">
          <el-input
            v-model="editStatusForm.banReason"
            :disabled="editStatusForm.status == 1 ? false : true"
          ></el-input>
        </el-form-item>

        <el-form-item label="附加时间" prop="addTime">
          <el-row>
            <el-col :span="8">
              <el-input v-model="editStatusForm.addTime"></el-input>
            </el-col>
            <el-col :span="8">
              <span>分钟</span>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>

      <!-- 底部 -->
      <span slot="footer">
        <el-button @click="editStudentVisible = false">取 消</el-button>
        <el-button type="primary" @click="editStuManage">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 注意事项 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <div class="second-content bg-purple">
          注意:请在考试开始前校准服务器屏幕右下方的时钟，
          考试过程中调整时钟将导致全体考生需要重新登录系统!
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Changemachine from "@/components/invigilate/changemachine.vue";
import Editdate from "@/components/invigilate/editdate.vue";
export default {
  name: "invExamRoom",
  components: { Changemachine, Editdate },
  data() {
    return {
      tableData: [],
      // 改变状态
      changeEnabled(data, val) {

        let ids = data.studentId
        console.log(data.id)
        var str1;
        if (val === 0) {
          str1 = "上线";
        } else {
          str1 = "下线";
        }
        this.$confirm(
          '此操作将 "' + str1 + '" ' + data.studentName + ", 是否继续？",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            // eslint-disable-next-line no-undef
            this.axios
              .get(this.$http.httpUrl(`/testStudent/selectStudentState`), {
                params: {
                  ids
                }
              })
              .then((response) => {

              });
            // crudBanner
            //   .changeStatus(data)
            //   .then(() => {

            //     // eslint-disable-next-line no-undef
            //     this.crud.notify(str1 + "成功", "success");
            //   })
            //   .catch((err) => {
            //     if (data.adFlag === 1) {
            //       data.adFlag = 0;
            //     } else {
            //       data.adFlag = 1;
            //     }
            //     console.log(err.data.message);
            //   });
          })
          .catch(() => {
            this.getInvExamStuList()
          });

      },

      options: [
        {
          value: "选项1",
          label: "仅显示在线考生",
        },
        {
          value: "选项2",
          label: "仅显示缺考考生",
        },
      ],

      //控制修改考试时间对话框
      editTimeVisible: false,
      //修改考试时间表单
      editExamTimeForm: {
        id: 0,
        name: "",
        startTime: null,
        endTime: null,
        text: "",
      },

      //控制管理考生对话框
      editStudentVisible: false,
      //管理考生表单
      editStatusForm: {
        stuid: "1",
        stuname: "覃XX",
        //存取考试状态
        status: 0,
        //禁考理由
        banReason: "",
        //附加时间
        addTime: "0",
      },
      //全部考生的考试状态
      examStatus: 1,
      //换机开关
      changemachineDialog: false,
      editDateDialog: false,

      pageNumber: 1, //当前页
      pageSize: 10,
      totalCount: 0, //总数
      loading: false,
      keyword: "",
      value: "",
      input: "",
      sselectInvStudentList: [],
      currentTime: null,
        timeEnd:null,
    };
  },
  created() {
    this.getInvExamStuList();
    this.getInvExamTask();

  },
  mounted() {
      this.timeEnd = setInterval(() => {
      this.closeStudentExam()// 
    }, 60000);
  },
  methods: {

    // 修改状态
    selectUpdateStudentState() {
      let ids = ''
      this.$confirm(
        "此操作将修改" + this.sselectInvStudentList.length + "个学生状态, 是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {

          this.sselectInvStudentList.forEach((value) => {
            if(value.status == 0){
               ids += value.studentId + ','
            }
           
          })
          this.axios
            .get(this.$http.httpUrl(`/testStudent/selectStudentState`), {
              params: {
                ids
              }
            })
            .then((response) => {
              this.$message.success("操作成功");
              this.getInvExamStuList()
            });

        })
        .catch(() => {

        });

    },
    // 禁止学员考试
    closeStudentExam() {
      this.getCurrentTime();
      if (this.currentTime > this.editExamTimeForm.endTime) {
           let ids = ''
           this.pageNumber=1
          this.pageSize = 300
          this.getInvExamStuList()
          this.tableData.forEach((item) => {
            console.log(item)
            if(item.status==0){
              ids += item.studentId + ','
            }
            
          })
          console.log('closeStudentExam', ids)
          this.axios
            .get(this.$http.httpUrl(`/testStudent/closeState`), {
              params: {
                ids
              },
            })
            .then((response) => {
                this.$message("考试时间已经结束，已禁止学员考试");
            });
      
           this.pageSize = 10
           window.clearInterval(this.timeEnd)
      
      } 
    this.getInvExamStuList()
    },
    selectInvStudent(val) {
      this.sselectInvStudentList = val
      console.log("this.sselectInvStudentList", this.sselectInvStudentList)
    },
    //监考端导出学生答题卡
    downLoadStudentAnswer() {
      this.axios
        .post(this.$http.httpUrl("/exam/downLoadStudentQuestionAnswer"),
          this.sselectInvStudentList
        )
        .then((response) => {
          location.href = this.$http.httpUrl("/exam/downLoad");
          this.$message.success("正在下载压缩包");
        });

    },



    keyup() {
      if (this.judgeNull(this.keyword)) {
        this.getInvExamStuList();
      }
    },

    //判空
    judgeNull(str) {
      if (str == "") return true;
      var regu = "^[ ]+$";
      var re = new RegExp(regu);
      return re.test(str);
    },

    //获取监考端考生列表
    getInvExamStuList() {
      this.axios
        .get(this.$http.httpUrl(`/testStudent/invStudentList`), {
          params: {
            pageNumber: this.pageNumber,
            pageSize: this.pageSize,
            studentName: this.keyword,
          },
        })
        .then((response) => {
          this.tableData = response.data.data.dataList;
          this.totalCount = response.data.data.total;
          // this.closeStudentExam()
          console.log("this.tableData", this.tableData);
        });
    },

    //获取监考考试任务信息
    getInvExamTask() {
      this.axios
        .get(this.$http.httpUrl(`/exam/selectByIdExamTask`), {})
        .then((response) => {
          this.editExamTimeForm = response.data.data;
          // console.log("任务信息editExamTimeForm",this.editExamTimeForm)
        });
    },

    //修改监考考试任务信息
    updateExamTask() {
      var that = this;
      that.axios
        .get(that.$http.httpUrl(`/exam/updateExamTask`), {
          params: {
            id: this.editExamTimeForm.id,
            name: this.editExamTimeForm.name,
            startTime: this.editExamTimeForm.startTime,
            endTime: this.editExamTimeForm.endTime,
            text: this.editExamTimeForm.text,
          },
        })
        .then((response) => {
          if (response.data.code === 1) {
            that.$message({
              type: "success",
              message: response.data.message,
            });
          }
          that.editTimeVisible = false;
        });
      that.getInvExamTask();
    },

    //点击dialog 取消按钮时触发
    closeForm() {
      this.changemachineDialog = false;
      this.editDateDialog = false;
      //自动刷新
      // location. reload()
    },
    closeDialog() {
      this.closeForm();
    },
    //打开换机配置
    openChangemaChine() {
      this.changemachineDialog = true;
    },
    //打开修改时间
    openEditDate() {
      this.editDateDialog = true;
    },

    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      _this.gettime = yy + "-" + mm + "-" + dd + " " + hh + ":" + mf + ":" + ss;
      this.currentTime = _this.gettime;
      // console.log("当前时间", this.currentTime);
    },

    //开启考试
    openExam() {
      this.$confirm("您确定要开启此次考试", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.examStatus = !this.examStatus;
          console.log("考试状态:" + this.examStatus);
          this.$message({
            type: "success",
            message: "已全部开启考试!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
      // this.examStatus = !this.examStatus;
      // console.log("考试状态:" + this.examStatus);
      // this.$message("已全部关闭考试");
    },
    //关闭考试
    closeExam() {

      this.$confirm("您确定要关闭此次考试", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.examStatus = !this.examStatus;
          console.log("考试状态:" + this.examStatus);
          this.$message({
            type: "warning",
            message: "已全部关闭考试!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
        });
    },

    showStu(item) {
      console.log("学生信息", item);
      this.editStudentVisible = true;
      this.editStatusForm.stuid = item.id;
      this.editStatusForm.stuid = item.loginName;
      this.editStatusForm.stuname = item.studentName;
      // this.editStatusForm.status = item.status
    },

    //修改学生信息
    editStuManage() {
      console.log("修改完成，打印输出", this.editStatusForm);
    },

    handleSizeChange(val) {
      this.pageNumber = 1;
      this.pageSize = val;
      this.getInvExamStuList();
    },
    handleCurrentChange(val) {
      this.pageNumber = val;
      this.getInvExamStuList();
    },
    //清空
    clearTable() {
      this.$confirm("此操作将永久清空数据库, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios.get(this.$http.httpUrl(`/clearTable`))
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

  },
};
</script>

<style>
.hander_item {
  height: 20px;
}
button.el-button.el-button--danger {
  margin-left: 40px;
}
.second-content {
  border-radius: 15px;
  min-height: 30px;
  font-size: 16px;
  text-align: center;
  background: #e4e7ed;
  margin: 5px;
  text-align: center;
}
.demo1 {
  color: #2828ff;
  cursor: pointer; /*鼠标悬停变小手*/
}
</style>